//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;

namespace Eas.WebCrawler.PlugIns.UrlProcessedHandlers {
    /// <summary>Handles <see cref="Eas.WebCrawler.Interfaces.WebCrawlerEvents.UrlProcessed"/> events by saving out the processed Uri (not the request's contents) to a file.</summary>
    public class VisitedListCreatingUrlProcessor : UrlProcessedHandler {
        private static object _Lock = new object();
        /// <summary>The name of the file to which Urls will be written.</summary>
        /// <remarks>Backing field for the FileName property.</remarks>
        /// <seealso cref="FileName"/>
        private string _FileName;

        /// <summary>The name of the file to which Urls will be written.</summary>
        public string FileName {
            get { return _FileName; }
        }

        /// <summary>Constructs a <see cref="VisitedListCreatingUrlProcessor"/> from the name of the file to which visited Uris will be saved.</summary>
        /// <param name="fileName">The name of the file to which visited Uris will be saved.</param>
        public VisitedListCreatingUrlProcessor(string fileName) {
            _FileName = fileName;
        }

        #region UrlProcessedHandler Members
        /// <summary>Handles the <see cref="Eas.WebCrawler.Interfaces.WebCrawlerEvents.UrlProcessed"/> event fired by the web crawler when registered to do so.</summary>
        /// <param name="sender">The sender of the event.</param>
        /// <param name="argument">Details of the processed url.</param>
        /// <remarks>This implementation saves out the visited url to a file.</remarks>
        public void UrlProcessed(object sender, Eas.WebCrawler.Interfaces.UrlCompletedEventArgs argument) {
            lock (_Lock) {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_FileName, true)) {
                    writer.WriteLine(argument.State.Request.Uri.ToString());
                }
            }
        }
        #endregion
    }
}
